#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A股中长期投资分析系统 - 主程序
一键运行完整的8步分析流程
"""

import sys
import os
import time
from datetime import datetime

def print_banner():
    """打印系统横幅"""
    print("=" * 80)
    print("           A股中长期投资分析系统 - 完整流程执行器")
    print("=" * 80)
    print(f"🕐 开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("🎯 目标: 筛选出3只最具潜力的中长期投资标的")
    print("📋 流程: 8步完整分析 (筛选→技术→基本面→综合→深度→预测→建议)")
    print("=" * 80)

def run_step(step_num, step_name, script_name):
    """运行单个分析步骤"""
    print(f"\n🚀 执行第{step_num}步: {step_name}")
    print("-" * 60)
    
    start_time = time.time()
    
    try:
        # 动态导入并执行模块
        if script_name == "advanced_stock_screener":
            from advanced_stock_screener import AdvancedStockScreener
            screener = AdvancedStockScreener()
            screener.screen_candidate_stocks()
            
        elif script_name == "technical_analysis_system":
            from technical_analysis_system import TechnicalAnalysisSystem
            analyzer = TechnicalAnalysisSystem()
            analyzer.run_technical_analysis()
            
        elif script_name == "fundamental_analysis_system":
            from fundamental_analysis_system import FundamentalAnalysisSystem
            analyzer = FundamentalAnalysisSystem()
            analyzer.run_fundamental_analysis()
            
        elif script_name == "comprehensive_ranking_system":
            from comprehensive_ranking_system import ComprehensiveRankingSystem
            ranking = ComprehensiveRankingSystem()
            ranking.run_comprehensive_ranking()
            
        elif script_name == "deep_analysis_system":
            from deep_analysis_system import DeepAnalysisSystem
            analyzer = DeepAnalysisSystem()
            analyzer.run_deep_analysis()
            
        elif script_name == "trend_prediction_system":
            from trend_prediction_system import TrendPredictionSystem
            predictor = TrendPredictionSystem()
            predictor.run_trend_prediction()
            
        elif script_name == "investment_recommendation_system":
            from investment_recommendation_system import InvestmentRecommendationSystem
            recommender = InvestmentRecommendationSystem()
            recommender.run_investment_recommendation()
            
        else:
            print(f"❌ 未知的脚本名称: {script_name}")
            return False
            
        elapsed_time = time.time() - start_time
        print(f"✅ 第{step_num}步完成，耗时: {elapsed_time:.1f}秒")
        return True
        
    except Exception as e:
        elapsed_time = time.time() - start_time
        print(f"❌ 第{step_num}步执行失败: {e}")
        print(f"⏱️ 执行时间: {elapsed_time:.1f}秒")
        return False

def main():
    """主程序入口"""
    print_banner()
    
    # 定义8步分析流程
    analysis_steps = [
        (1, "数据获取与验证", "基础数据获取"),  # 这步已完成，跳过
        (2, "股票筛选系统", "advanced_stock_screener"),
        (3, "技术分析系统", "technical_analysis_system"),
        (4, "基本面分析系统", "fundamental_analysis_system"),
        (5, "综合评分与排序", "comprehensive_ranking_system"),
        (6, "深度分析选中股票", "deep_analysis_system"),
        (7, "趋势预测系统", "trend_prediction_system"),
        (8, "投资建议生成", "investment_recommendation_system")
    ]
    
    total_start_time = time.time()
    successful_steps = 0
    failed_steps = []
    
    for step_num, step_name, script_name in analysis_steps:
        if step_num == 1:
            print(f"\n✅ 第1步: 数据获取与验证 - 已完成")
            successful_steps += 1
            continue
            
        success = run_step(step_num, step_name, script_name)
        
        if success:
            successful_steps += 1
        else:
            failed_steps.append((step_num, step_name))
            
        # 步骤间短暂暂停
        time.sleep(1)
    
    # 执行总结
    total_elapsed_time = time.time() - total_start_time
    
    print("\n" + "=" * 80)
    print("                          执行总结")
    print("=" * 80)
    print(f"🕐 总执行时间: {total_elapsed_time:.1f}秒")
    print(f"✅ 成功步骤: {successful_steps}/8")
    print(f"❌ 失败步骤: {len(failed_steps)}/8")
    
    if failed_steps:
        print(f"\n失败的步骤:")
        for step_num, step_name in failed_steps:
            print(f"   • 第{step_num}步: {step_name}")
    
    if successful_steps == 8:
        print(f"\n🎉 恭喜！完整的8步投资分析流程全部执行成功！")
        print(f"📊 分析结果已保存到相应的CSV文件和报告中")
        print(f"💡 请查看 '投资分析报告.md' 获取具体投资建议")
    elif successful_steps >= 6:
        print(f"\n⚠️ 大部分步骤执行成功，可以获得基本的投资建议")
        print(f"💡 建议检查失败步骤的具体错误信息")
    else:
        print(f"\n❌ 执行失败步骤较多，建议检查系统环境和依赖")
        
    print(f"\n🔚 分析完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("=" * 80)

if __name__ == "__main__":
    main()
